package controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import pojo.Sdepts;
import pojo.Status;
import pojo.Tokens;
import service.SdeptService;
import service.TokenService;
import service.impl.SdeptServiceImpl;
import service.impl.TokenServiceImpl;
import utils.JSONUtils;
import utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/api/sdept")
@RestController
public class SdeptController {

    private SdeptService sdeptService = new SdeptServiceImpl();
    private TokenService tokenService = new TokenServiceImpl();


    @GetMapping
    public void allSdept(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String accessToken = request.getHeader("AccessToken");
        Tokens tokens = tokenService.queryByToken(accessToken);
        JSONObject jsonObject = new JSONObject();
        if (TokenUtils.decrypt(tokens)) {
            List<Sdepts> sdeptsList = sdeptService.queryAllSdept();

            jsonObject.put(Status.CODE, Status.OK);
            jsonObject.put(Status.MSG, "所有系部查询成功");

            jsonObject.put("data", sdeptsList);

        } else {
            jsonObject.put(Status.CODE, Status.UNAUTHORIZED);
            jsonObject.put(Status.MSG, "请登录");

        }

        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }

    @PostMapping("/create")
    public void create(@RequestBody Sdepts sdept, HttpServletRequest request, HttpServletResponse response) throws IOException {

        System.out.println(sdept);
        JSONObject jsonObject = new JSONObject();
        String accessToken = request.getHeader("AccessToken");
        Tokens tokens = tokenService.queryByToken(accessToken);

        if (TokenUtils.decrypt(tokens)) {
            int i = sdeptService.SaveSdept(sdept);
            if (i == -1) {
                jsonObject.put(Status.CODE, Status.BAD_REQUEST);
                jsonObject.put(Status.MSG, sdept.getName() + "系添加失败");
            } else {
                jsonObject.put(Status.CODE, Status.OK);
                jsonObject.put(Status.MSG, sdept.getName() + "系添加成功");
            }
        } else {
            jsonObject.put(Status.CODE, Status.UNAUTHORIZED);
            jsonObject.put(Status.MSG, "请登录");

        }
        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }


}
